package org.example.service.Impl;

import org.example.common.ResponseMessage;
import org.example.entity.User;
import org.example.entity.dto.RegisterDto;
import org.example.entity.dto.UserDto;
import org.example.exception.ServiceException;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.example.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService { //实现类实现了服务层的接口
    @Autowired
    private UserMapper userMapper;

    /**
     * 新增用户
     * @param userDto
     * @return
     */
    @Override
    public ResponseMessage addUser(UserDto userDto) {
        User userNew = new User();
        BeanUtils.copyProperties(userDto,userNew); // 将userDto的属性复制到userNew对象里面
        int count = userMapper.insert(userNew);
        if (count > 0){
            return ResponseMessage.success(userNew);
        }
            return ResponseMessage.error();
    }

    @Override
    public List<User> getUserByDept(String Dept){
        User userNew = new User();
//        BeanUtils.copyProperties(dept,userNew);
        userNew.setDept(Dept);
        return userMapper.find(Dept);
    }

    @Override
    public RegisterDto register(RegisterDto registerDto) {
        User dbUserNew = userMapper.selectByUsername(registerDto.getUserName());
        if (dbUserNew != null){
            //抛出一个自定义的异常
            throw new ServiceException("用户名已存在！");
        }
            userMapper.save(registerDto);
            return registerDto;
    }

    //验证用户名的合法性
    @Override
    public User login(User user) { //加密密码+返回token（jwt），通过token获取用户信息
        User dbUser = userMapper.selectByUsername(user.getUserName());
        if (dbUser == null){
            //抛出一个自定义的异常
            throw new ServiceException("用户名或密码错误！");
        }
        if (!user.getPassWord().equals(dbUser.getPassWord())){
            throw new ServiceException("用户名或密码错误！");
        }
        // 生成token
        String token = TokenUtils.createToken(dbUser.getID().toString(),dbUser.getPassWord());
        dbUser.setToken(token);
        return dbUser;
    }
}
